package app.server.project.core.syndb;

import java.lang.invoke.SerializedLambda;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class FieldNameExtractor {
    /**
     * 从Getter方法引用提取字段名
     *
     * @param getter 方法引用，必须是getter的
     * @return 字段名
     */
    public static <T, R> String extractFieldNameFromGetter(Getter<T, R> getter) {
        try {
            //反射获取writeReplace方法
            Method writeReplace = getter.getClass().getDeclaredMethod("writeReplace");
            writeReplace.setAccessible(true);
            //调用writeReplace方法
            SerializedLambda serializedLambda = (SerializedLambda) writeReplace.invoke(getter);
            //获取实现方法，也就是方法引用对应的方法名
            String methodName = serializedLambda.getImplMethodName();
            return extractFieldName(methodName);
        } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    private static String extractFieldName(String methodName) {
        String fieldName;
        if (methodName.startsWith("is")) {
            fieldName = methodName.substring(2);
        } else if (methodName.startsWith("get")) {
            fieldName = methodName.substring(3);
        } else {
            throw new IllegalArgumentException("method name should start with 'is' or 'get'");
        }
        return Character.toLowerCase(fieldName.charAt(0)) + fieldName.substring(1);
    }
}